package com.tianze.tzkf;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.Guideline;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.tianze.tzkf.base.BaseActivity;
import com.tianze.tzkf.bean.BannerListBean;
import com.tianze.tzkf.bean.BindSmilePayBean;
import com.tianze.tzkf.function.login.CheckPwdActivity;
import com.tianze.tzkf.net.RetrofitFactory;
import com.tianze.tzkf.utils.GlideImageLoader;
import com.tianze.tzkf.utils.LongClickUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by Zcyang on 2018/12/20.
 */
public class BannerActivity extends BaseActivity {

    private static String TAG = BannerActivity.class.toString();


    @BindView(R.id.bv_advert)
    Banner banner;
    @BindView(R.id.iv_banner_setting)
    ImageView ivBannerSetting;
    @BindView(R.id.iv_banner_wifi)
    ImageView ivBannerWifi;
    @BindView(R.id.textView9)
    TextView textView9;
    @BindView(R.id.iv_banner_bottom_logo1)
    ImageView ivBannerBottomLogo1;
    @BindView(R.id.textView8)
    TextView textView8;
    @BindView(R.id.iv_banner_bottom_logo2)
    ImageView ivBannerBottomLogo2;
    @BindView(R.id.guideline11)
    Guideline guideline11;

    private WifiInfo wifiInfo = null;        //获得的Wifi信息
    private WifiManager mWifiManager = null;    //Wifi管理器
    private int level;                        //信号强度值
    private String screen;//信号强度值


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 如果收到正确的消息就获取WifiInfo，改变图片并显示信号强度
                case 1:
                    ivBannerWifi.setImageResource(R.drawable.ic_signal_wifi_4_bar_black_24dp);
                   /* Toast.makeText(BannerActivity.this,
                            "信号强度：" + level + " 信号最好", Toast.LENGTH_SHORT)
                            .show();*/
                    break;
                case 2:
                    ivBannerWifi.setImageResource(R.drawable.ic_signal_wifi_3_bar_black_24dp);
                    /*Toast.makeText(BannerActivity.this,
                            "信号强度：" + level + " 信号较好", Toast.LENGTH_SHORT)
                            .show();*/
                    break;
                case 3:
                    ivBannerWifi.setImageResource(R.drawable.ic_signal_wifi_2_bar_black_24dp);
                    /*Toast.makeText(BannerActivity.this,
                            "信号强度：" + level + " 信号一般", Toast.LENGTH_SHORT)
                            .show();*/
                    break;
                case 4:
                    ivBannerWifi.setImageResource(R.drawable.ic_signal_wifi_1_bar_black_24dp);
                   /* Toast.makeText(BannerActivity.this,
                            "信号强度：" + level + " 信号较差", Toast.LENGTH_SHORT)
                            .show();*/
                    break;
                case 5:
                    ivBannerWifi.setImageResource(R.drawable.ic_signal_wifi_off_black_24dp);
                    /*Toast.makeText(BannerActivity.this,
                            "信号强度：" + level + " 无信号", Toast.LENGTH_SHORT)
                            .show();*/
                    break;

                default:
                    //以防万一
                    ivBannerWifi.setImageResource(R.drawable.ic_signal_wifi_off_black_24dp);
                    /*Toast.makeText(BannerActivity.this, "无信号",
                            Toast.LENGTH_SHORT).show();*/
            }


        }
    };
    private BannerListBean.DataBean data;


    @Override
    protected void initData() {
        getBannerList();
        getSmilePayNumber();


        // 获得WifiManager
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);

        // 使用定时器,每隔5秒获得一次信号强度值
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                wifiInfo = mWifiManager.getConnectionInfo();
                //获得信号强度值
                level = wifiInfo.getRssi();
                //根据获得的信号强度发送信息
                if (level <= 0 && level >= -50) {
                    Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);
                } else if (level < -50 && level >= -70) {
                    Message msg = new Message();
                    msg.what = 2;
                    handler.sendMessage(msg);
                } else if (level < -70 && level >= -80) {
                    Message msg = new Message();
                    msg.what = 3;
                    handler.sendMessage(msg);
                } else if (level < -80 && level >= -100) {
                    Message msg = new Message();
                    msg.what = 4;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.what = 5;
                    handler.sendMessage(msg);
                }

            }

        }, 1000, 5000);


        LongClickUtils.setLongClick(handler, ivBannerSetting, 2000, new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bannerListBean", data);
                close_WebSocket();
                close_Icard();
                goToActivity(CheckPwdActivity.class, bundle);
               // removeCurrentActivity();
                return true;
            }
        });



    }

    @Override
    protected void reflshData() {

//        initSockect();
    }

    private void getBannerList() {

        String token = readToken().getToken();


        Map<String, String> request = new HashMap<>();
        request.put("token", token);
        request.put("screen", screen);//screen

        Observable<BannerListBean> getSmilePayNumber = RetrofitFactory.getInstance(TAG).getBannerList(request);
        getSmilePayNumber.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BannerListBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BannerListBean bannerListBean) {
                        if (bannerListBean.getCode() == 10001) {
                            if (!bannerListBean.getData().getBanner().equals("")) {
                                initBannerPic(bannerListBean.getData().getBanner());
                            } else {
                                List<BannerListBean.DataBean.BannerBean> list_banner = new ArrayList<>();
                                initBannerPic(list_banner);
                            }
                            data = bannerListBean.getData();
                            Glide.with(BannerActivity.this).load(data.getLogo()).into(ivBannerBottomLogo1);
                            Glide.with(BannerActivity.this).load(data.getSlogan()).into(ivBannerBottomLogo2);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    /**
     * 绑定设备
     */
    private void getSmilePayNumber() {

        String token = readToken().getToken();

        String serialNumber = getSerialNumber();


        Map<String, String> request = new HashMap<>();
        request.put("token", token);
        request.put("port", "pos");
        request.put("SN", serialNumber);

        Observable<BindSmilePayBean> getSmilePayNumber = RetrofitFactory.getInstance(TAG).getSmilePayNumber(request);
        getSmilePayNumber.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BindSmilePayBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BindSmilePayBean bindSmilePayBean) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    //通过反射获取ro.serialno
    public static String getSerialNumber() {

        String serial = null;

        try {

            Class<?> c = Class.forName("android.os.SystemProperties");

            Method get = c.getMethod("get", String.class);

            serial = (String) get.invoke(c, "ro.serialno");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return serial;

    }


    /**
     * 显示banner图片
     *
     * @param banner
     */
    private void initBannerPic(List<BannerListBean.DataBean.BannerBean> banner) {
        List<String> list = new ArrayList<>();

        list.add("http://img1.cache.netease.com/catchpic/9/9E/9ECB8D4D42F899358DB8249E0DE85579.jpg");
        list.add("http://www.yipuwuyou.com/file/upload/201708/17/091601911907.jpg");
        list.add("http://www.chinairn.com/UserFiles/image/20180531/20180531151202_4389.jpg");
        list.add("http://img1.zczj.com/images/20180608/20180608102117.jpg");
        list.add("http://www.downxia.com/uploadfiles/2016/0901/20160901024900399.jpg");

        List<String> url = new ArrayList<>();
        for (int i = 0; i < banner.size(); i++) {
            url.add(banner.get(i).getPath());
        }
        //设置banner样式
        this.banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器
        this.banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        if (banner.size() == 0) {
            this.banner.setImages(list);
        } else {
            this.banner.setImages(url);
        }
        //设置banner动画效果
        //        banner.setBannerAnimation(Transformer.DepthPage);
        //设置标题集合（当banner样式有显示title时）
        //        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        this.banner.isAutoPlay(true);
        //设置轮播时间
        this.banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        this.banner.setIndicatorGravity(BannerConfig.NOT_INDICATOR);

        //设置轮播图点击事件
        this.banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Log.e("BannerClick", ">>>>>>>>");
//                goToActivity(HomeActivity.class, null);
                //        goToActivity(WebSocketActivity.class,null);
            }
        });
        //banner设置方法全部调用完毕时最后调用
        this.banner.start();

    }

    @Override
    protected void initTitle() {
        Configuration mConfiguration = this.getResources().getConfiguration(); //获取设置的配置信息
        int ori = mConfiguration.orientation; //获取屏幕方向
        if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {
            //横屏
            screen = "horizon";
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制为竖屏
        } else if (ori == mConfiguration.ORIENTATION_PORTRAIT) {
            //竖屏
            screen = "vertical";
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
        }
//        initSockect();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_banner;
    }

    @Override
    protected void isNetConnect(boolean isNetChanges) {

    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    @OnClick({R.id.iv_banner_setting, R.id.iv_banner_wifi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_banner_setting:
                break;
            case R.id.iv_banner_wifi:
                break;
        }
    }


}


